package com.asiainfo.wexin;

import com.asiainfo.wexin.api.WeiXinApi;
import com.asiainfo.wexin.awt.MyImageShowFrame;
import com.asiainfo.wexin.model.Article;
import com.asiainfo.wexin.model.BizData;
import com.asiainfo.wexin.model.WxResultBody;
import com.asiainfo.wexin.okhttp.MyCookieStore;
import com.asiainfo.wexin.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 程序主入口
 *
 * @author zsq
 * @version 1.0
 * @date 2021/3/31 10:57
 */
public class Application {

    private static MyImageShowFrame myImageShowFrame;

    /**
     * 主入口
     *
     * @param args
     */
    public static void main(String[] args) throws IOException {
        //图片显示控件
        myImageShowFrame = new MyImageShowFrame();

        // 1. POST请求开始登录接口，初始化cookie
        String sessionid = "" + System.currentTimeMillis() + (int) (Math.random() * 100);
        WxResultBody wxResultBody = WeiXinApi.startLogin(sessionid);
        System.out.println("---请求开始登录接口 返回结果:" + wxResultBody.toString());

        // 2. 请求获取二维码图片接口，得到流
        InputStream qrCodeIs = WeiXinApi.getQRCode();
        //转成图片显示
        myImageShowFrame.showImage(qrCodeIs);

        // 3.轮询二维码状态接口
        FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                while (true) {
                    WxResultBody askQRCode = WeiXinApi.askQRCode();
                    Integer status = askQRCode.getStatus();
                    if (status == 3) {
                        System.out.println("二维码已过期");
                        return 3;
                    } else if (status == 4) {
                        System.out.println("已扫码，等待确认");
                    } else if (status == 1) {
                        System.out.println("已确认登录，请稍后...");
                        return 1;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        while (true) {
            Thread queryThread = new Thread(futureTask);
            queryThread.start();
            if (!futureTask.isDone()) {
                System.out.println("--正在查询扫码状态，请尽快扫码！");
            }

            try {
                Integer integer = futureTask.get();
                if (integer == 1) {
                    //说明扫码确认成功，否则重新获取图片
                    //关闭图片显示
                    myImageShowFrame.close();
                    break;
                } else {
                    //重新获取二维码图片显示
                    myImageShowFrame.showImage(WeiXinApi.getQRCode());
                }
            } catch (Exception e) {
                System.out.println("查询接口出错了");
                break;
            }
        }

        // 4.确认登录后，请求登录接口，拿到登录状态的cookie
        WxResultBody bizlogin = WeiXinApi.bizlogin();
        //重定向地址
        String redirect_url = bizlogin.getRedirect_url();
        //解析成键值对
        Map<String, String> loginRes = HttpUtils.parseQueryParams(redirect_url);
        //得到token
        String token = loginRes.get("token");
        //设置全局token值
        MyCookieStore.setToken(token);

        System.out.println("---恭喜你，登录成功！");
        // ok

        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("----请输入你想搜索的公众号：");
            String gzName = scanner.nextLine();
            if (StringUtils.isBlank(gzName)) {
                System.out.println("--不能搜空的");
                continue;
            }
            System.out.println("开始搜索：" + gzName);
            WxResultBody<List<BizData>> searchBiz = WeiXinApi.searchBiz(gzName);
            System.out.println("----请按序号选择公众号");
            List<BizData> list = searchBiz.getList();
            int ii = 1;
            for (BizData bizData : list) {
                System.out.println(ii + "：" + bizData.getNickname());
                ii++;
            }

            int index = 0;
            while (true) {
                try {
                    String numStr = scanner.nextLine();
                    index = Integer.parseInt(numStr);
                    if (index < 0 || index > list.size()) {
                        System.out.println("超出范围了，重选!!");
                    }
                    break;
                } catch (Exception e) {
                    System.out.println("你得输入一个数字!!!!");
                }
            }

            System.out.println("list" + list);
            BizData select = list.get(index - 1);
            System.out.println("select" + select);
            System.out.printf("--好的，开始搜索【%s】的文章...%n", select.getNickname());

            WxResultBody<List<Article>> findExList = WeiXinApi.findExList(select.getFakeid());
            System.out.println("findExList" + findExList);
            List<Article> exList = findExList.getApp_msg_list();
            for (Article article : exList) {
                System.out.println("---文章标题：" + article.getTitle()+"，文章链接："+article.getLink());
            }
        }
    }
}
